<?php

namespace Muyuxuanpay\threePay\src\hk\JsPayment;

use Muyuxuanpay\pay\common\Tool;
use Muyuxuanpay\threePay\BaseTrait;
use Muyuxuanpay\threePay\JsPayment;
use Muyuxuanpay\threePay\src\hk\CommonTrait;
use Muyuxuanpay\tool\Mtool;

class Pay implements JsPayment
{
    use BaseTrait;
    use CommonTrait;
    protected $must = [
        'merch_no'    =>"商户编号",
        'pn'          =>"SAAS终端号",
        'public_key'  =>"公钥",
        'private_key' =>"秘钥",
    ];

    protected $typeList = [
        'WX',//微信支付
        'ALI',//支付宝支付
        'UNIONQR',//云闪付
    ];
    protected $defaultConfig = [
        'format'=>'JSON',
        'charset'=>'UTF-8',
        'sign_type'=>'RSA2',
        'version'=>'1.0',
    ];

    public function pay(string $type,string $out_trade_no,$total_amount,string $body,string $appid,string $openid,array $event=[])
    {
        $type = strtoupper($type);
        if(!in_array($type,$this->typeList)){
            throw new \Exception('不支持的支付方式');
        }
        // 验证
        $this->verify();
        if($type==='WX'){
            return $this->wechat($out_trade_no,$total_amount,$body,$appid,$openid,$event);
        }
    }

    protected function wechat(string $out_trade_no,$total_amount,string $body,string $appid,string $openid,array $event=[])
    {
        $now = date('YmdHis');

        $requestData = [
            'biz_type'      => 'prePay_V2',
            'merch_no'      => $this->config['merch_no'],
            'pn'            => $this->config['pn'],
            'req_id'        => $out_trade_no,
            'pay_type'      => 'WX',//WX：微信支付 ALI：支付宝支付 UNIONQR：云闪付
            'pay_mode'      => 'JSAPI',//NATIVE：扫码支付  JSAPI：JSAPI支付
            'appid'         => $appid,
            'openid'        => $openid,
            'out_trade_no'  => $out_trade_no,
            'total_amount'  => $total_amount,
            'remark'        => $body,
            'limit_pay'     => '0',
            'notify_url'    => $this->config['pay_notify'],
        ];
        $requestData['sign'] = $this->getSign($requestData, $this->config['private_key']);
        $requestRus = $this->post($this->URL['wx_pub'], $requestData);
        var_dump($requestRus);
        die;
        if($requestRus['code']!='00000'){
            $msg = $requestRus['msg']?$requestRus['msg']:($requestRus['sub_msg']?$requestRus['sub_msg']:'请求失败');
            throw new \Exception($msg);
        }
        if(isset($requestRus['sub_code'])&&$requestRus['sub_code']=='FAIL'){
            throw new \Exception($requestRus['sub_msg']);
        }
        $content = $requestRus['content'];
        if(!empty($content['pay_info'])){
            if(is_string($content['pay_info'])){
                $content['pay_info'] = Mtool::json_decode($content['pay_info']);
            }
        }
        return $content;
    }
}